<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <title>JSON和模型之间转换iOS框架：MJExtension | Grx Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="MJExtension是一套字典和模型之间互相转换的超轻量级框架 MJExtension能完成的功能字典（JSON）–&amp;gt;模型（Model）模型（Model）–&amp;gt;字典（JSON）字典数组（JSON Array）–&amp;gt;模型数组（Model Array）模型数组（Model Array）–&amp;gt;字典数组（JSON Array）">
<meta property="og:type" content="article">
<meta property="og:title" content="JSON和模型之间转换iOS框架：MJExtension">
<meta property="og:url" content="http://yoursite.com/2016/05/18/JSON和模型之间转换iOS框架：MJExtension/index.html">
<meta property="og:site_name" content="Grx Blog">
<meta property="og:description" content="MJExtension是一套字典和模型之间互相转换的超轻量级框架 MJExtension能完成的功能字典（JSON）–&amp;gt;模型（Model）模型（Model）–&amp;gt;字典（JSON）字典数组（JSON Array）–&amp;gt;模型数组（Model Array）模型数组（Model Array）–&amp;gt;字典数组（JSON Array）">
<meta property="og:updated_time" content="2016-05-18T09:08:52.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JSON和模型之间转换iOS框架：MJExtension">
<meta name="twitter:description" content="MJExtension是一套字典和模型之间互相转换的超轻量级框架 MJExtension能完成的功能字典（JSON）–&amp;gt;模型（Model）模型（Model）–&amp;gt;字典（JSON）字典数组（JSON Array）–&amp;gt;模型数组（Model Array）模型数组（Model Array）–&amp;gt;字典数组（JSON Array）">
  
    <link rel="alternative" href="/atom.xml" title="Grx Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="http://img3.imgtn.bdimg.com/it/u=2738905542,2894070565&amp;fm=21&amp;gp=0.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Grx</a></h1>
		</hgroup>

		
		<p class="header-subtitle">自我管理，知识管理，时间管理，阅读，语音写作，思维导图</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
						<div class="icon-wrap icon-me hide" data-idx="3">
							<div class="user"></div>
							<div class="shoulder"></div>
						</div>
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
						<li>关于我</li>
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/">主页</a></li>
				        
							<li><a href="/tags/life">随笔</a></li>
				        
							<li><a href="/archives">所有文章</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
								<a class="github" target="_blank" href="#" title="github">github</a>
					        
								<a class="weibo" target="_blank" href="#" title="weibo">weibo</a>
					        
								<a class="rss" target="_blank" href="#" title="rss">rss</a>
					        
								<a class="zhihu" target="_blank" href="#" title="zhihu">zhihu</a>
					        
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						<a href="/tags/OC/" style="font-size: 20px;">OC</a> <a href="/tags/RAC/" style="font-size: 10px;">RAC</a> <a href="/tags/Xcode/" style="font-size: 15px;">Xcode</a> <a href="/tags/appledoc/" style="font-size: 10px;">appledoc</a> <a href="/tags/hexo/" style="font-size: 15px;">hexo</a>
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://blog.devtang.com">唐巧的博客</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://beyondvincent.com">破船之家</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://limboy.me">无网不剩</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://msching.github.io">码农人生</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://yulingtianxia.com">玉令天下</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://blog.leichunfeng.com">雷纯锋的技术博客</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://jax.cnblogs.com">包建强</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://blog.cnbang.net">bang</a>
			        
			        </div>
				</section>
				

				
				
				<section class="switch-part switch-part4">
				
					<div id="js-aboutme">知识管理，时间管理，自我管理，阅读，语音写作，思维导图，Wiz，TimeMeter</div>
				</section>
				
			</div>
		</div>
	</header>				
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Grx</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
			
				<img lazy-src="http://img3.imgtn.bdimg.com/it/u=2738905542,2894070565&amp;fm=21&amp;gp=0.jpg" class="js-avatar">
			
			</div>
			<hgroup>
			  <h1 class="header-author">Grx</h1>
			</hgroup>
			
			<p class="header-subtitle">自我管理，知识管理，时间管理，阅读，语音写作，思维导图</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/tags/life">随笔</a></li>
		        
					<li><a href="/archives">所有文章</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="#" title="github">github</a>
			        
						<a class="weibo" target="_blank" href="#" title="weibo">weibo</a>
			        
						<a class="rss" target="_blank" href="#" title="rss">rss</a>
			        
						<a class="zhihu" target="_blank" href="#" title="zhihu">zhihu</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap"><article id="post-JSON和模型之间转换iOS框架：MJExtension" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2016/05/18/JSON和模型之间转换iOS框架：MJExtension/" class="article-date">
  	<time datetime="2016-05-18T08:08:03.000Z" itemprop="datePublished">2016-05-18</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JSON和模型之间转换iOS框架：MJExtension
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
	<div class="article-tag tagcloud">
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/OC/">OC</a></li></ul>
	</div>

        

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="MJExtension是一套字典和模型之间互相转换的超轻量级框架-MJExtension能完成的功能"><a href="#MJExtension是一套字典和模型之间互相转换的超轻量级框架-MJExtension能完成的功能" class="headerlink" title="MJExtension是一套字典和模型之间互相转换的超轻量级框架 MJExtension能完成的功能"></a>MJExtension是一套字典和模型之间互相转换的超轻量级框架 MJExtension能完成的功能</h5><p>字典（JSON）–&gt;模型（Model）<br>模型（Model）–&gt;字典（JSON）<br>字典数组（JSON Array）–&gt;模型数组（Model Array）<br>模型数组（Model Array）–&gt;字典数组（JSON Array）</p>
<a id="more"></a>
<ul>
<li><a href="#1">Getting Started 【开始使用】</a><ul>
<li><a href="#1.1">Features 【能做什么】</a></li>
<li><a href="#1.2">Installation 【安装】</a></li>
</ul>
</li>
<li><a href="#2">Examples 【示例】</a><ul>
<li><a href="#2.1">JSON -&gt; Model</a></li>
<li><a href="#2.2">JSONString -&gt; Model</a></li>
<li><a href="#2.3">Model contains model</a></li>
<li><a href="#2.4">Model contains model-array</a></li>
<li><a href="#2.5">Model name - JSON key mapping</a></li>
<li><a href="#2.6">JSON array -&gt; model array</a></li>
<li><a href="#2.7">Model -&gt; JSON</a></li>
<li><a href="#2.8">Model array -&gt; JSON array</a></li>
<li><a href="#2.9">Core Data</a></li>
<li><a href="2.10">Coding</a></li>
<li><a href="#2.11">Camel -&gt; underline</a></li>
<li><a href="#2.12">NSString -&gt; NSDate, nil -&gt; @””</a></li>
<li><a href="#2.13">More use cases</a></li>
</ul>
</li>
</ul>
<p></p><h2 id="1">Getting Started【开始使用】</h2><p></p>
<p></p><h3 id="1.1">Features【能做什么】</h3><p></p>
<ul>
<li>MJExtension是一套字典和模型之间互相转换的超轻量级框架</li>
<li>JSON –&gt; Model、Core Data Model</li>
<li>JSONString –&gt; Model、Core Data Model</li>
<li>Model、Core Data Model –&gt; JSON</li>
<li>JSON Array –&gt; Model Array、Core Data Model Array</li>
<li>JSONString –&gt; Model Array、Core Data Model Array</li>
<li>Model Array、Core Data Model Array –&gt; JSON Array</li>
<li>Coding all properties of model in one line code.<ul>
<li>只需要一行代码，就能实现模型的所有属性进行Coding（归档和解档）</li>
</ul>
</li>
</ul>
<p></p><h3 id="1.2"> Installation【安装】</h3><p></p>
<h4>From CocoaPods【使用CocoaPods】</h4><br>       pod ‘MJExtension’<br><br><h4>Manually【手动导入】</h4>

<ul>
<li>Drag all source files under floder MJExtension to your project.【将MJExtension文件夹中的所有源代码拽入项目中】</li>
<li><p>Import the main header file：#import “MJExtension.h”【导入主头文件：#import “MJExtension.h”】</p>
<pre><code>MJExtension.h
MJConst.h               MJConst.m
MJFoundation.h          MJFoundation.m
MJProperty.h            MJProperty.m
MJType.h                MJType.m
NSObject+MJCoding.h     NSObject+MJCoding.m
NSObject+MJProperty.h   NSObject+MJProperty.m
NSObject+MJKeyValue.h   NSObject+MJKeyValue.m
</code></pre></li>
</ul>
<h2 id="Examples【示例】"><a href="#Examples【示例】" class="headerlink" title=" Examples【示例】"></a><h2 id="2"> Examples【示例】</h2></h2><h4 id="2.1">The most simple JSON -&gt; Model【最简单的字典转模型】</h4>

<pre><code>   typedef enum {
       SexMale,
       SexFemale
   } Sex;

  @interface User : NSObject
  @property (copy, nonatomic) NSString *name;
  @property (copy, nonatomic) NSString *icon;
  @property (assign, nonatomic) unsigned int age;
  @property (copy, nonatomic) NSString *height;
  @property (strong, nonatomic) NSNumber *money;
  @property (assign, nonatomic) Sex sex;
  @property (assign, nonatomic, getter=isGay) BOOL gay;
  @end

  /***********************************************/

  NSDictionary *dict = @{
      @&quot;name&quot; : @&quot;Jack&quot;,
      @&quot;icon&quot; : @&quot;lufy.png&quot;,
      @&quot;age&quot; : @20,
      @&quot;height&quot; : @&quot;1.55&quot;,
      @&quot;money&quot; : @100.9,
      @&quot;sex&quot; : @(SexFemale),
      @&quot;gay&quot; : @&quot;true&quot;
 //   @&quot;gay&quot; : @&quot;1&quot;
 //   @&quot;gay&quot; : @&quot;NO&quot;
 };

 // JSON -&gt; User
User *user = [User mj_objectWithKeyValues:dict];

NSLog(@&quot;name=%@, icon=%@, age=%zd, height=%@, money=%@, sex=%d, gay=%d&quot;, user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1
</code></pre><h4 id="2.2">JSONString -&gt; Model【JSON字符串转模型】</h4><br>       // 1.Define a JSONString<br>       NSString <em>jsonString = @”{\”name\”:\”Jack\”, \”icon\”:\”lufy.png\”, \”age\”:      20}”;<br><br>       // 2.JSONString -&gt; User<br>       User </em>user = [User mj_objectWithKeyValues:jsonString];<br><br>       // 3.Print user’s properties<br>       NSLog(@”name=%@, icon=%@, age=%d”, user.name, user.icon, user.age);<br>       // name=Jack, icon=lufy.png, age=20<br><br><h4 id="2.3">Model contains model【模型中嵌套模型】</h4><br>       @interface Status : NSObject<br>       @property (copy, nonatomic) NSString <em>text;<br>       @property (strong, nonatomic) User </em>user;<br>       @property (strong, nonatomic) Status <em>retweetedStatus;<br>       @end<br><br>       /<strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></em>/<br><br>       NSDictionary <em>dict = @{<br>       @”text” : @”Agree!Nice weather!”,<br>       @”user” : @{<br>           @”name” : @”Jack”,<br>           @”icon” : @”lufy.png”<br>       },<br>       @”retweetedStatus” : @{<br>           @”text” : @”Nice weather!”,<br>           @”user” : @{<br>               @”name” : @”Rose”,<br>               @”icon” : @”nami.png”<br>           }<br>       }<br>       };<br><br>       // JSON -&gt; Status<br>       Status </em>status = [Status mj_objectWithKeyValues:dict];<br><br>       NSString <em>text = status.text;<br>       NSString </em>name = status.user.name;<br>       NSString <em>icon = status.user.icon;<br>       NSLog(@”text=%@, name=%@, icon=%@”, text, name, icon);<br>       // text=Agree!Nice weather!, name=Jack, icon=lufy.png<br><br>       NSString </em>text2 = status.retweetedStatus.text;<br>       NSString <em>name2 = status.retweetedStatus.user.name;<br>       NSString </em>icon2 = status.retweetedStatus.user.icon;<br>       NSLog(@”text2=%@, name2=%@, icon2=%@”, text2, name2, icon2);<br>       // text2=Nice weather!, name2=Rose, icon2=nami.png<br><br><h4 id="2.4">Model contains model-array【模型中有个数组属性，数组里面又要装着其他模型】</h4><br>       @interface Ad : NSObject<br>       @property (copy, nonatomic) NSString <em>image;<br>       @property (copy, nonatomic) NSString </em>url;<br>       @end<br><br>       @interface StatusResult : NSObject<br>       /<strong> Contatins status model <em>/<br>       @property (strong, nonatomic) NSMutableArray </em>statuses;<br>       /</strong> Contatins ad model <em>/<br>       @property (strong, nonatomic) NSArray </em>ads;<br>       @property (strong, nonatomic) NSNumber <em>totalNumber;<br>       @end<br><br>       /<strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></em>/<br><br>       // Tell MJExtension what type model will be contained in statuses and ads.<br>       [StatusResult mj_setupObjectClassInArray:^NSDictionary <em>{<br>       return @{<br>                  @”statuses” : @”Status”,<br>                  // @”statuses” : [Status class],<br>                  @”ads” : @”Ad”<br>                  // @”ads” : [Ad class]<br>              };<br>       }];<br>       // Equals: StatusResult.m implements +mj_objectClassInArray method.<br><br>       NSDictionary </em>dict = @{<br>       @”statuses” : @[<br>                         @{<br>                             @”text” : @”Nice weather!”,<br>                             @”user” : @{<br>                                 @”name” : @”Rose”,<br>                                 @”icon” : @”nami.png”<br>                             }<br>                         },<br>                         @{<br>                             @”text” : @”Go camping tomorrow!”,<br>                             @”user” : @{<br>                                 @”name” : @”Jack”,<br>                                 @”icon” : @”lufy.png”<br>                             }<br>                         }<br>                     ],<br>       @”ads” : @[<br>                    @{<br>                        @”image” : @”ad01.png”,<br>                        @”url” : @”<a href="http://www.ad01.com" target="_blank" rel="external">http://www.ad01.com</a>“<br>                    },<br>                    @{<br>                        @”image” : @”ad02.png”,<br>                        @”url” : @”<a href="http://www.ad02.com" target="_blank" rel="external">http://www.ad02.com</a>“<br>                    }<br>                ],<br>       @”totalNumber” : @”2014”<br>       };<br><br>       // JSON -&gt; StatusResult<br>       StatusResult <em>result = [StatusResult mj_objectWithKeyValues:dict];<br><br>       NSLog(@”totalNumber=%@”, result.totalNumber);<br>       // totalNumber=2014<br><br>       // Printing<br>       for (Status </em>status in result.statuses) {<br>       NSString <em>text = status.text;<br>       NSString </em>name = status.user.name;<br>       NSString <em>icon = status.user.icon;<br>       NSLog(@”text=%@, name=%@, icon=%@”, text, name, icon);<br>       }<br>       // text=Nice weather!, name=Rose, icon=nami.png<br>       // text=Go camping tomorrow!, name=Jack, icon=lufy.png<br><br>       // Printing<br>       for (Ad </em>ad in result.ads) {<br>       NSLog(@”image=%@, url=%@”, ad.image, ad.url);<br>       }<br>       // image=ad01.png, url=<a href="http://www.ad01.com" target="_blank" rel="external">http://www.ad01.com</a><br>       // image=ad02.png, url=<a href="http://www.ad02.com" target="_blank" rel="external">http://www.ad02.com</a><br><br><h4 id="2.5">Model name - JSON key mapping【模型中的属性名和字典中的key不相同(或者需要多级映射)】</h4><br>       @interface Bag : NSObject<br>       @property (copy, nonatomic) NSString <em>name;<br>       @property (assign, nonatomic) double price;<br>       @end<br><br>       @interface Student : NSObject<br>       @property (copy, nonatomic) NSString </em>ID;<br>       @property (copy, nonatomic) NSString <em>desc;<br>       @property (copy, nonatomic) NSString </em>nowName;<br>       @property (copy, nonatomic) NSString <em>oldName;<br>       @property (copy, nonatomic) NSString </em>nameChangedTime;<br>       @property (strong, nonatomic) Bag <em>bag;<br>       @end<br><br>       /<strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></em>/<br><br>       // How to map<br>       [Student mj_setupReplacedKeyFromPropertyName:^NSDictionary <em>{<br>       return @{<br>                  @”ID” : @”id”,<br>                  @”desc” : @”desciption”,<br>                  @”oldName” : @”name.oldName”,<br>                  @”nowName” : @”name.newName”,<br>                  @”nameChangedTime” : @”name.info[1].nameChangedTime”,<br>                  @”bag” : @”other.bag”<br>              };<br>       }];<br>       // Equals: Student.m implements +mj_replacedKeyFromPropertyName method.<br><br>       NSDictionary </em>dict = @{<br>       @”id” : @”20”,<br>       @”desciption” : @”kids”,<br>       @”name” : @{<br>           @”newName” : @”lufy”,<br>           @”oldName” : @”kitty”,<br>           @”info” : @[<br>                    @”test-data”,<br>                    @{<br>                            @”nameChangedTime” : @”2013-08”<br>                      }<br>                  ]<br>       },<br>       @”other” : @{<br>           @”bag” : @{<br>               @”name” : @”a red bag”,<br>               @”price” : @100.7<br>           }<br>       }<br>       };<br><br>       // JSON -&gt; Student<br>       Student *stu = [Student mj_objectWithKeyValues:dict];<br><br>       // Printing<br>       NSLog(@”ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@”,<br>       stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime);<br>       // ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08<br>       NSLog(@”bagName=%@, bagPrice=%f”, stu.bag.name, stu.bag.price);<br>       // bagName=a red bag, bagPrice=100.700000<br><br><h4 id="2.6">JSON array -&gt; model array【将一个字典数组转成模型数组】</h4>

<pre><code>NSArray *dictArray = @[
                  @{
                      @&quot;name&quot; : @&quot;Jack&quot;,
                      @&quot;icon&quot; : @&quot;lufy.png&quot;
                  },
                  @{
                      @&quot;name&quot; : @&quot;Rose&quot;,
                      @&quot;icon&quot; : @&quot;nami.png&quot;
                  }
              ];

 // JSON array -&gt; User array
 NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray];

 // Printing
 for (User *user in userArray) {
NSLog(@&quot;name=%@, icon=%@&quot;, user.name, user.icon);
}
// name=Jack, icon=lufy.png
// name=Rose, icon=nami.png
</code></pre><h4 id="2.7">Model -&gt; JSON【将一个模型转成字典】</h4>

<pre><code>// New model
User *user = [[User alloc] init];
user.name = @&quot;Jack&quot;;
user.icon = @&quot;lufy.png&quot;;

Status *status = [[Status alloc] init];
status.user = user;
status.text = @&quot;Nice mood!&quot;;

// Status -&gt; JSON
NSDictionary *statusDict = status.mj_keyValues;
NSLog(@&quot;%@&quot;, statusDict);
/*
{
  text = &quot;Nice mood!&quot;;
  user =     {
  icon = &quot;lufy.png&quot;;
  name = Jack;
};
}
*/

// More complex situation
Student *stu = [[Student alloc] init];
stu.ID = @&quot;123&quot;;
stu.oldName = @&quot;rose&quot;;
stu.nowName = @&quot;jack&quot;;
stu.desc = @&quot;handsome&quot;;
stu.nameChangedTime = @&quot;2018-09-08&quot;;

Bag *bag = [[Bag alloc] init];
bag.name = @&quot;a red bag&quot;;
bag.price = 205;
stu.bag = bag;

NSDictionary *stuDict = stu.mj_keyValues;
NSLog(@&quot;%@&quot;, stuDict);
/*
{
ID = 123;
bag =     {
    name = &quot;\U5c0f\U4e66\U5305&quot;;
    price = 205;
};
desc = handsome;
nameChangedTime = &quot;2018-09-08&quot;;
nowName = jack;
oldName = rose;
}
*/
</code></pre><h4 id="2.8">Model array -&gt; JSON array【将一个模型数组转成字典数组】</h4><br>       // New model array<br>       User <em>user1 = [[User alloc] init];<br>       user1.name = @”Jack”;<br>       user1.icon = @”lufy.png”;<br><br>       User </em>user2 = [[User alloc] init];<br>       user2.name = @”Rose”;<br>       user2.icon = @”nami.png”;<br><br>       NSArray <em>userArray = @[user1, user2];<br><br>       // Model array -&gt; JSON array<br>       NSArray </em>dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];<br>       NSLog(@”%@”, dictArray);<br>       /<em><br>       (<br>       {<br>          icon = “lufy.png”;<br>          name = Jack;<br>       },<br>       {<br>          icon = “nami.png”;<br>          name = Rose;<br>       }<br>       )
       </em>/<br><br><h4 id="2.9">Core Data</h4><br>       NSDictionary <em>dict = @{<br>                         @”name” : @”Jack”,<br>                         @”icon” : @”lufy.png”,<br>                         @”age” : @20,<br>                         @”height” : @1.55,<br>                         @”money” : @”100.9”,<br>                         @”sex” : @(SexFemale),<br>                         @”gay” : @”true”<br>                     };<br><br>       // This demo just provide simple steps<br>        NSManagedObjectContext </em>context = nil;<br>        User <em>user = [User mj_objectWithKeyValues:dict context:context];<br><br>        [context save:nil];<br><br><h4 id="2.10">Coding</h4><br>        #import “MJExtension.h”<br><br>        @implementation Bag<br>        // NSCoding Implementation<br>        MJExtensionCodingImplementation<br>        @end<br><br>        /<strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></em>/<br><br>        // what properties not to be coded<br>        [Bag mj_setupIgnoredCodingPropertyNames:^NSArray <em>{<br>       return @[@”name”];<br>        }];<br>        // Equals: Bag.m implements +mj_ignoredCodingPropertyNames method.<br><br>        // Create model<br>        Bag </em>bag = [[Bag alloc] init];<br>        bag.name = @”Red bag”;<br>        bag.price = 200.8;<br><br>        NSString <em>file = [NSHomeDirectory()  stringByAppendingPathComponent:@”Desktop/bag.data”];<br>        // Encoding<br>        [NSKeyedArchiver archiveRootObject:bag toFile:file];<br><br>        // Decoding<br>        Bag </em>decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];<br>        NSLog(@”name=%@, price=%f”, decodedBag.name, decodedBag.price);<br>        // name=(null), price=200.800000<br><h4 id="2.11">Camel -&gt; underline【统一转换属性名（比如驼峰转下划线）】</h4><br>        // Dog<br>        #import “MJExtension.h”<br><br>        @implementation Dog<br>       + (NSString <em>)mj_replacedKeyFromPropertyName121:(NSString </em>)propertyName<br>        {<br>           // nickName -&gt; nick_name<br>           return [propertyName mj_underlineFromCamel];<br>        }<br>        @end<br><br>        // NSDictionary<br>        NSDictionary <em>dict = @{<br>                       @”nick_name” : @”旺财”,<br>                       @”sale_price” : @”10.5”,<br>                       @”run_speed” : @”100.9”<br>                       };<br>        // NSDictionary -&gt; Dog<br>        Dog </em>dog = [Dog mj_objectWithKeyValues:dict];<br><br>        // printing<br>        NSLog(@”nickName=%@, scalePrice=%f runSpeed=%f”, dog.nickName, dog.salePrice, dog.runSpeed);<br><br><h4 id="2.12">NSString -&gt; NSDate, nil -&gt; @””【过滤字典的值（比如字符串日期处理为NSDate、字符串nil处理为@””）】</h4>

<pre><code>// Book
#import &quot;MJExtension.h&quot;

@implementation Book
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property
{
    if ([property.name isEqualToString:@&quot;publisher&quot;]) {
    if (oldValue == nil) return @&quot;&quot;;
} else if (property.type.typeClass == [NSDate class]) {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @&quot;yyyy-MM-dd&quot;;
    return [fmt dateFromString:oldValue];
}

    return oldValue;
}
@end

// NSDictionary
NSDictionary *dict = @{
                  @&quot;name&quot; : @&quot;5分钟突破iOS开发&quot;,
                  @&quot;publishedTime&quot; : @&quot;2011-09-10&quot;
                  };
// NSDictionary -&gt; Book
Book *book = [Book mj_objectWithKeyValues:dict];

// printing
NSLog(@&quot;name=%@, publisher=%@, publishedTime=%@&quot;, book.name, book.publisher, book.publishedTime);
</code></pre><p></p><h4 id="2.13">More use cases【更多用法】</h4><p></p>
<ul>
<li>Please reference to NSObject+MJKeyValue.h and NSObject+MJCoding.h</li>
</ul>
<hr>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
  
    <a href="/2016/05/13/移动端数据库新王者-realm/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">移动端数据库新王者:realm</div>
      <strong class="article-nav-caption">></strong>
    </a>
  
</nav>

  
</article>


<div class="share_jia">
	<!-- JiaThis Button BEGIN -->
	<div class="jiathis_style">
		<span class="jiathis_txt">Share to: &nbsp; </span>
		<a class="jiathis_button_facebook"></a> 
    <a class="jiathis_button_twitter"></a>
    <a class="jiathis_button_plus"></a> 
    <a class="jiathis_button_tsina"></a>
		<a class="jiathis_button_cqq"></a>
		<a class="jiathis_button_douban"></a>
		<a class="jiathis_button_weixin"></a>
		<a class="jiathis_button_tumblr"></a>
    <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	</div>
	<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
	<!-- JiaThis Button END -->
</div>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="JSON和模型之间转换iOS框架：MJExtension" data-title="JSON和模型之间转换iOS框架：MJExtension" data-url="http://yoursite.com/2016/05/18/JSON和模型之间转换iOS框架：MJExtension/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"true"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>




</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2016 Grx
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="http://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script src="/js/main.js"></script>






<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  </div>
</body>
</html>